package yxk.task.moka;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yxk.utils.BosUtil;
import yxk.utils.HttpRequestUtil;

import javax.json.Json;
import javax.json.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 摩卡服务方法类
 */
public class MoKaService {
    private static final Log LOG = LogFactory.getLog(MoKaService.class);
    private DynamicObject MOKAORG;
    private DynamicObject MOKAGW;
    private DynamicObject MOKAUSER;

    /**
     1、当前系统没有，同步时有：新增一个部门
     2、当前系统有，同步时也有：更新已经存在的部门信息。如果同步时有，当前系统部门状态标识为删除，更新后，状态改为正常。
     3、当前系统有，同步时没有时：部门打标已删除，需要手动进入 Moka 系统中将该部门合并到其他部门进行删除。
     * @param param 请求参数
     * @param toKen token
     */
    public void setMoKaOrg(List<JSONObject> param,String toKen){
        DynamicObject mokaorg = getMOKAORG();
        String url = mokaorg.getString("nwg5_url");
        JSONObject json=new JSONObject();
        json.put("departments",param);
        Map map=new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        try {
            String results = HttpRequestUtil.getPutResult(url, map, json.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.setMaKaOrg.results:{}",results);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<JSONObject> getListOrg(){
        List<JSONObject> list=new ArrayList<>();
        QFilter qFilter=new QFilter("level", QCP.not_equals, 0)
                .and(new QFilter("iscurrentversion",QCP.equals,'1'))
                .and(new QFilter("enable",QCP.equals ,'1'));
        DynamicObject[] loaded = BusinessDataServiceHelper.load("haos_adminorghr", "id,number,name,parent,level", qFilter.toArray());
        for (DynamicObject row : loaded) {
            JSONObject param=new JSONObject();
            param.put("departmentCode",row.getString("number"));//编码
            param.put("name",row.getString("name"));//名称
            DynamicObject parent = row.getDynamicObject("parent");
            if(parent != null) {
                param.put("parentCode", parent.getString("number"));//上级编码
            }else{
                param.put("parentCode", "0");//上级编码
            }
            param.put("sequence",row.getInt("level"));
            list.add(param);
        }
        LOG.info("MoKaService.getListOrg.list:{}",list);
        return list;
    }

    /**
     * 摩卡新增岗位接口
     */
    public String setMoKaHRPosition(JSONObject param,String toKen){
        DynamicObject mokagw = getMOKAGW();
        String url = mokagw.getString("nwg5_url")+"?currentHireMode=1";
        Map map = new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        try {
            LOG.info("MoKaService.setMoKaHRPosition.param:[{}],usr:[{}],Map: [{}]",param,url,map);
            String results = HttpRequestUtil.getPostResult(url, map, param.toString(), "application/json;charset=utf-8");
                LOG.info("MoKaService.setMoKaHRPosition.results:{}",results);
            JSONObject jsonObject = JSONObject.parseObject(results);
            JSONObject data = jsonObject.getJSONObject("data");
            String jobId = data.getString("jobId");
            return jobId;
        }catch (Exception e){
            LOG.info("MoKaService.setMoKaHRPosition.e:{}",e);
            e.printStackTrace();
        }
        return null;
    }

    public String setSchoolMoKaHRPosition(JSONObject param,String toKen){
        DynamicObject mokagw = getMOKAGW();
        String url = mokagw.getString("nwg5_url")+"?currentHireMode=2";
        Map map = new HashMap<>();
        //获取社招编码改为校招
        JSONObject customData = param.getJSONObject("customData");
        if(customData != null){
            String number = customData.getString("235876");
            String name = customData.getString("242959");
            JSONObject json=new JSONObject();
            json.put("238719",number);
            json.put("225248",name);
            param.put("customData",json);
        }

        map.put("Authorization","Bearer "+toKen);
        try {
            LOG.info("MoKaService.setMoKaHRPosition.param:[{}],usr:[{}],Map: [{}]",param,url,map);
            String results = HttpRequestUtil.getPostResult(url, map, param.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.setMoKaHRPosition.results:{}",results);
            JSONObject jsonObject = JSONObject.parseObject(results);
            JSONObject data = jsonObject.getJSONObject("data");
            String jobId = data.getString("jobId");
            return jobId;
        }catch (Exception e){
            LOG.info("MoKaService.setMoKaHRPosition.e:{}",e);
            e.printStackTrace();
        }
        return null;
    }


    /**
     *摩卡更新岗位接口
     */
    public String updateMoKaHRPosition(JSONObject param,String toKen,String jobId){
        DynamicObject mokagw = getMOKAGW();
        String url = mokagw.getString("nwg5_secreturl")+jobId;
        Map map=new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        try {
            String results = HttpRequestUtil.getPutResult(url, map, param.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.updateMoKaHRPosition.results:{}",results);
            JSONObject jsonObject = JSONObject.parseObject(results);
            JSONObject data = jsonObject.getJSONObject("data");
            return data.getString("jobId");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public void setListPerson(List<JSONObject> users,String toKen){
        DynamicObject mokagw = getMOKAUSER();
        String url = mokagw.getString("nwg5_url");
        JSONObject param=new JSONObject();
        param.put("usersInfo",users);
        Map map = new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        try {
            LOG.info("MoKaService.setListPerson.param:{},url:{}",param,url);
            String results = HttpRequestUtil.getPostResult(url, map, param.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.setListPerson.results:{}",results);
        }catch (Exception e){
            LOG.info("MoKaService.setListPerson.e:{}",e);
            e.printStackTrace();
        }
    }

    public Map<String,JSONObject> getMapPosition(){
        Map<String,JSONObject> map=new HashMap<>();
        QFilter qFilter=new QFilter("iscurrentversion", QCP.equals,'1')
                .and(new QFilter("nwg5_mokaid", QCP.not_equals,null).or(new QFilter("school_mokaid", QCP.not_equals,null)));
        DynamicObject[] position = BusinessDataServiceHelper.load("hbpm_positionhr", "number,name,adminorg,parent,enable,workplace", qFilter.toArray());
        for (DynamicObject row : position) {
            JSONObject data=new JSONObject();
            String number = row.getString("number");
            String name = row.getString("name");
            //岗位名称
            data.put("title",name);
            //岗位状态
            int anInt = row.getInt("enable");
            if(1 == anInt) {
                data.put("status", "open");
            }else{
                data.put("status", "closed");
            }
            data.put("commitment","全职");
            //行政组织
            DynamicObject adminorg = row.getDynamicObject("adminorg");
            data.put("departmentCode",adminorg.getString("number"));
            JSONObject json=new JSONObject();
            json.put("235876",number);      //摩卡生产环境金蝶编码ID
            json.put("242959",name);        //摩卡生产环境金蝶职位名称
            //json.put("410047618",number); //摩卡测试环境金蝶编码ID
            data.put("customData",json);
            map.put(number,data);
        }
        return map;
    }

    public List<List<JSONObject>> getUsersInfo(String toKen){
        List<List<JSONObject>> list=new ArrayList<>();
        QFilter qFilter=new QFilter("datastatus", QCP.equals,'1')
                .and(new QFilter("businessstatus", QCP.equals,'1'))
                .and(new QFilter("iscurrentversion", QCP.equals,'1'))
                .and(new QFilter("empposrel.isprimary", QCP.equals,'1'));
        DynamicObject[] loaded = BusinessDataServiceHelper.load("hspm_ermanfile", "name,number,person,affiliateadminorg,empentrel", qFilter.toArray());
        List numberList=new ArrayList<>();
        for (DynamicObject single : loaded) {
            DynamicObject person = single.getDynamicObject("person");
            numberList.add(person.getString("number"));
        }
        QFilter qF=new QFilter("person.number", QCP.in,numberList)
                .and(new QFilter("iscurrentversion", QCP.equals,'1'));
        //获取个人联系方式
        DynamicObject[] percontacts = BusinessDataServiceHelper.load("hrpi_percontact", "person,phone,peremail,busemail", qF.toArray());
        Map<String,Map<String,String>> map=new HashMap<>();
        for (DynamicObject percontact : percontacts) {
            DynamicObject person = percontact.getDynamicObject("person");
            String phone = percontact.getString("phone"); //电话号码
            String peremail = percontact.getString("busemail"); //公司电子邮箱

            Map<String,String> percon=new HashMap<>();
            percon.put("phone",phone);
            percon.put("peremail",peremail);

            map.put(person.getString("number"),percon);
        }

        //摩卡人员map
        Map<String,JSONObject> userInfoMap=new HashMap<>();
        List<JSONArray> arrays = queryUserInfoLists(toKen);
        for (int i = 0; i < arrays.size(); i++) {
            JSONArray array = arrays.get(i);
            for (int j = 0; j < array.size(); j++) {
                JSONObject json = array.getJSONObject(j);
                String number = json.getString("number");
                if(number != null){
                    userInfoMap.put(number,json);
                }
            }
        }

        List<JSONObject> persons=new ArrayList<>();
        int i=0;
        for (DynamicObject row : loaded) {
            JSONObject person=new JSONObject();
            DynamicObject pers = row.getDynamicObject("person");
            String number = pers.getString("number");
         //   Boolean bool = queryUserInfo(number, toKen);

            Map<String, String> percon = map.get(number);
            if(percon !=null ){
                String phone = percon.get("phone").substring(4);
                person.put("phone",phone);//电话号码
                person.put("email",percon.get("peremail"));//邮箱
            }
            person.put("name",row.getString("name"));//姓名
            person.put("number",number);//工号
            JSONObject jsonObject = userInfoMap.get(number);
            if(jsonObject == null) {
                //137337 内推人ID / 137338 前台ID / 137339 面试官ID / 137343 管理员ID
                //137340 用人经理ID / 137341 高级用人经理ID / 137342 HRID / 137344 超级管理员ID
                person.put("roleId", "137337");//角色ID
            }
            DynamicObject adminorg = row.getDynamicObject("affiliateadminorg");
            List<String> code=new ArrayList<>();
            code.add(adminorg.getString("number"));
            person.put("departmentCode",code);//部门编码
            DynamicObject empentrel = row.getDynamicObject("empentrel");
            DynamicObject laborrelStatus = empentrel.getDynamicObject("laborrelstatus");
            String laborrelNumber = laborrelStatus.getString("number");
            if("1080_S".equals(laborrelNumber)) {
                person.put("deactivated", 1);//0-不禁用 1-禁用
            }else{
                person.put("deactivated", 0);
            }
            person.put("uniqueType","number");//email或者number或者phone，判断此次传输时用来判断账号唯一性的标识
            person.put("autoActivated","1");//0-不自动激活，1-自动激活
            persons.add(person);
            i++;
            if(persons.size()==100 || loaded.length==i){
                list.add(persons);
                persons=new ArrayList<>();
            }

        }

        return list;
    }

    /**
     * 根据人员工号查询摩卡人员信息
     * @param number
     * @return
     */
    public Boolean queryUserInfo(String number,String toKen){
        DynamicObject mokagw = getMOKAUSER();
        String url = mokagw.getString("nwg5_secreturl");
        JSONObject param=new JSONObject();
        param.put("number",number);
        Map map=new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        try {
            String results = HttpRequestUtil.getPostResult(url, map, param.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.queryUserInfo.results:{}",results);
            JSONObject jsonObject = JSONObject.parseObject(results);
            JSONArray data = jsonObject.getJSONArray("data");
            if(data!=null && data.size()>0 ){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    public List<JSONArray> queryUserInfoLists(String toKen){
        DynamicObject mokagw = getMOKAUSER();
        List<JSONArray> list=new ArrayList<>();
        String url = mokagw.getString("nwg5_secreturl");
        JSONObject param=new JSONObject();
        param.put("deactivated",0);
        param.put("limit","500");
        param.put("order","asc");
        Map map=new HashMap<>();
        map.put("Authorization","Bearer "+toKen);
        String next = "";
        try {
            while (1==1) {
                String sendUrl=url;
                if(next != null && !"".equals(next)){
                    sendUrl = url+"?next="+next;
                }
                String results = HttpRequestUtil.getPostResult(sendUrl, map, param.toString(), "application/json;charset=utf-8");
                LOG.info("MoKaService.queryUserInfoLists.results:{}", results);
                JSONObject jsonObject = JSONObject.parseObject(results);
                JSONArray data = jsonObject.getJSONArray("data");
                if (data != null && data.size() > 0) {
                    list.add(data);
                     next = jsonObject.getString("next");
                     if("".equals(next) || next == null){
                         break;
                     }
                }else {
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }


    public String getMoKaToKen(){
        DynamicObject mokaorg = getMOKAORG();
        LOG.info("MoKaService.getMoKaToKen.mokaorg:{}",mokaorg);
        String toKenUrl = mokaorg.getString("nwg5_tokenurl");
        String user = mokaorg.getString("nwg5_user");
        String password = mokaorg.getString("nwg5_password");
        JSONObject body=new JSONObject();
        body.put("grantType","client_credentials");
        body.put("clientID",user);
        body.put("clientSecret",password);
        try {
            LOG.info("MoKaService.getMoKaToKen.body:{},url:{}",body,toKenUrl);
            String results = HttpRequestUtil.getPostResult(toKenUrl, null, body.toString(), "application/json;charset=utf-8");
            LOG.info("MoKaService.getMoKaToKen.results:{}",results);
            JSONObject jsonObject = JSONObject.parseObject(results);
            Integer code = jsonObject.getInteger("code");
            if(code==0){
                JSONObject data = jsonObject.getJSONObject("data");
                String token = data.getString("accessToken");
                return token;
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public DynamicObject getMOKAORG() {
        if( MOKAORG == null ){
            MOKAORG= BosUtil.getConfigUration("MOKAORG");
        }
        return MOKAORG;
    }

    public DynamicObject getMOKAGW() {
        if( MOKAGW == null ){
            MOKAGW= BosUtil.getConfigUration("MOKAGW");
        }
        return MOKAGW;
    }

    public DynamicObject getMOKAUSER() {
        if( MOKAUSER == null ){
            MOKAUSER= BosUtil.getConfigUration("MOKAUSER");
        }
        return MOKAUSER;
    }
}
